package com.hluck.goodweatherapp.data.repository;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.hluck.goodweatherapp.data.Constant;
import com.hluck.goodweatherapp.data.bean.LocationData;
import com.hluck.goodweatherapp.data.network.api.ApiService;
import com.hluck.mvvmlibrary.network.ApiType;
import com.hluck.mvvmlibrary.network.NetworkApi;
import com.hluck.mvvmlibrary.network.observer.BaseObserver;

/**
 * @Author： LJH
 * @Time： 2023/12/27
 * @description：
 */
public class SearchCityRepository {
    private static final String TAG = "SearchCityRepository";

    private SearchCityRepository(){}

    private static class SingleInstance{
        private static final SearchCityRepository INSTANCE = new SearchCityRepository();
    }

    public static SearchCityRepository getInstance(){
        return SingleInstance.INSTANCE;
    }

    /**
     * @param locationLiveData
     * @param failed
     * @param cityName
     * @param isExact
     */
    public void searchCity(MutableLiveData<LocationData> locationLiveData,MutableLiveData<String> failed,String cityName,boolean isExact){
        NetworkApi.createService(ApiService.class, ApiType.SEARCH).searchCity(cityName,isExact? Constant.EXACT:Constant.FUZZY)
                .compose(NetworkApi.applySchedulers(new BaseObserver<LocationData>() {
                    @Override
                    public void onSuccess(LocationData locationData) {
                        if (locationData == null) {
                            failed.postValue("搜索城市数据为null，请检查城市名称是否正确。");
                            return;
                        }
                        //请求接口成功返回数据，失败返回状态码
                        if (Constant.SUCCESS.equals(locationData.getCode())) {
                            locationLiveData.postValue(locationData);
                        } else {
                            failed.postValue(locationData.getCode());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        Log.e(TAG, "onFailure: " + e.getMessage());
                        failed.postValue(e.getMessage());
                    }
                }));
    }
}
